import {LrcParser, Lrc} from '@xiaohuohumax/lrc-parser';
import {parse, stringify, compile, decompile, ParsedASS} from 'ass-compiler';

const lrcParser = new LrcParser();
import assTextB from "./猪猪侠 - 陈洁丽.ass?raw"
import lrcTextB from "./猪猪侠 - 陈洁丽.lrc?raw"

/**
 * 一行歌词的信息
 * 时间全部是毫秒为单位
 */
export interface LyricsInfo {
  startTime: number; // 开始时间
  entTime: number;// 结束时间
  lrc: string[];// 歌词信息，一个一个字
  kTime: number[];// 每个歌词对应的显示时间单位毫秒，这个数组和上面的歌词数组一定是一样长的
  kTimeWithSE: number[][]; // 每个歌曲的开始时间和结束时间，开始时间下标0，结束时间下标1
  colorPer: number; // 0-100
}


function repairKTime(item: LyricsInfo, timeAvg: number) {
  for (let j = 0; j < item.lrc.length; j++) {
    if (!item.kTime[j] || item.kTime[j] === -1) {
      item.kTime[j] = timeAvg
    }
  }
  if (item.kTime.length > item.lrc.length) {
    item.kTime = item.kTime.slice(0, item.lrc.length)
  }
  // 生成字符的开始时间和结束时间
  item.kTimeWithSE = [
    [item.startTime,item.kTime[0] + item.startTime]
  ]
  for (let i = 1; i < item.kTime.length; i++) {
    let end = item.startTime
    for (let j = 0; j <= i; j++) {
      end+=item.kTime[j]
    }
    item.kTimeWithSE.push(
      [
        item.kTimeWithSE[i-1][1],
        end
      ]
    )
  }
}

export function assTextToLyricsInfos(assText: string = assTextB, musicLength: number = 211000): LyricsInfo[] {
  // ass 里面的k数字单位不是毫秒 要*10才是
  const parsedASS: ParsedASS = parse(assText);
  let result = parsedASS.events.dialogue.map((i, index) => {
    let startTime = Number(i.Start.toFixed(2)) * 1000
    let entTime = Number((i.End || musicLength).toFixed(2)) * 1000
    let timeAvg = Number(((entTime - startTime) / i.Text.combined.length).toFixed(2))
    let item: LyricsInfo = {
      startTime,
      entTime,
      lrc: i.Text.combined.split(''),
      kTime: i.Text.parsed.map(p => {
        if (p.tags?.[0]?.K) {
          return p.tags[0].K * 10
        }
        return -1
      }),
      kTimeWithSE: [],
      colorPer: 0,
    }
    repairKTime(item, timeAvg)
    return item
  })
  return result
}

export function lrcTextToLyricsInfos(lrcText: string = lrcTextB, musicLength: number = 211000): LyricsInfo[] {
  const lrc: Lrc = lrcParser.parser(lrcText);
  let result = lrc.lyrics.map(i => {
    let startTime = Number(i.start.toFixed(2))
    let entTime = Number((i.end || musicLength).toFixed(2))
    let timeAvg = Number(((entTime - startTime) / i.lyric.length).toFixed(2))
    let item: LyricsInfo = {
      startTime,
      entTime,
      lrc: i.lyric.split(''),
      kTime: [],
      kTimeWithSE: [],
      colorPer: 0,
    }
    repairKTime(item, timeAvg)
    return item
  })
  return result
}
